import path from './path.js';
class Route {
	constructor(vm) {
		//Vue全局上下文
	    this.vm = vm;
	}
	
	//判断一个变量是否为{}或者new Obj的对象类型
	isObject(obj) {
		return Object.prototype.toString.call(obj) === '[object Object]';
	}
	
	//编码带参数url
	stringify(obj){
		let val = '';
		if(!this.isObject(obj)) {
			throw new Error('请传入正确的对象');
		}else {
			delete obj.type;
			delete obj.isNeedLogin;
			
			let arr = Object.keys(obj)
			let string = '?';
			arr.forEach((key,index) => {
				let value;
				
				if(this.isObject(obj[key])){
					value = encodeURIComponent(JSON.stringify(obj[key]))
				}else value = obj[key];
				
				if(index != 0) string += '&&';
				string += `${key}=${value}`;
			})
			val = string === '?' ? '' : string;
		}
		return val;
	}
	
	//页面跳转函数
	//to 第二个参数为页面是否需要登陆才能进去
	//params: 对象参数，拼接在url后面
	//调用：this.$ma.route.error()
	to(url, isNeedLogin = false, params){
		return new Promise((resolve,reject) => {
			let uniFun = 'navigateTo';
			//如果是对象
			if (this.isObject(params)) {
				if (params.type) uniFun = params.type;
				//该页面是否需要登陆才能跳转
				if (params.isNeedLogin) isNeedLogin = params.isNeedLogin;
				url += this.stringify(params)
			} else {
				return uni.showToast({
					icon: 'none',
					title: '请传入正确的路由参数'
				})
			}
			//用户未登陆拦截
			if (isNeedLogin) this.vm.$store.dispatch('user/onLoginIntercept');
			//路由跳转
			uni[uniFun]({
				url,
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					console.log('跳转失败：',err)
					reject(err)
				}
			})
		})
	}
	
	getPath(){
		//to 第二个参数为页面是否需要登陆才能进去
		//params: 对象参数，拼接在url后面
		//调用：this.$ma.route.error()
		let route = {};
		Object.keys(path).forEach(pageName => {
			let page = path[pageName];
			route[pageName] = (params = {}) => this.to(page.url,page.isNeedLogin,params);
		})
		return route;
	}
	
}

export default Route;